const { verifyAccessToken } = require('../utils/tokenService');

/**
 * 认证中间件
 * 验证JWT token并设置req.user
 */
const authMiddleware = (req, res, next) => {
  try {
    // 从请求头获取Authorization token
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({
        code: 401,
        message: '未提供访问令牌'
      });
    }

    // 提取token
    const token = authHeader.substring(7);
    
    // 验证token
    const decoded = verifyAccessToken(token);
    
    if (!decoded) {
      return res.status(401).json({
        code: 401,
        message: '访问令牌无效或已过期'
      });
    }

    // 将用户信息设置到req.user，确保_id字段存在
    req.user = {
      _id: decoded.id,
      ...decoded
    };
    
    next();
  } catch (error) {
    console.error('认证中间件错误:', error);
    return res.status(401).json({
      code: 401,
      message: '认证失败'
    });
  }
};

module.exports = authMiddleware; 